//
//  LoginVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/7/21.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "LoginVC.h"
#import "Masonry.h"
#import "MainTabBarController.h"
#import "ForgetPassWordVC.h"
#import "RegisterVC1.h"


@interface LoginVC ()

@end

@implementation LoginVC
{
    UITextField *_phoneText;
    UITextField *_passWord;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"denglu_bg"]];
    imgView.frame = self.view.bounds;
    imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view insertSubview:imgView atIndex:0];
//    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"denglu_bg"]];
    [self initView];
}
- (void)initView{
    UIButton *imageBtn = [[UIButton alloc]init];
    [imageBtn setImage:[UIImage imageNamed:@"LOGO"] forState:UIControlStateNormal];
    [self.view addSubview:imageBtn];
    
    _phoneText = [[UITextField alloc]init];
    _phoneText.backgroundColor = RGBACOLOR(1, 1, 1, 0.3);
    _phoneText.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
    _phoneText.leftViewMode = UITextFieldViewModeAlways;
    _phoneText.layer.cornerRadius = 5;
    _phoneText.layer.borderWidth = 1;
    _phoneText.layer.borderColor = blackLineColore.CGColor;
    _phoneText.placeholder = @"请输入帐号(手机号码)";
    _phoneText.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:_phoneText];
    
    _passWord = [[UITextField alloc]init];
    _passWord.backgroundColor = RGBACOLOR(1, 1, 1, 0.3);
    _passWord.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
    _passWord.leftViewMode = UITextFieldViewModeAlways;
    _passWord.layer.cornerRadius = 5;
    _passWord.layer.borderWidth = 1;
    _passWord.layer.borderColor = blackLineColore.CGColor;
    _passWord.placeholder = @"请输入密码";
    _passWord.secureTextEntry = YES;
    [self.view addSubview:_passWord];
    
    UIButton *loginBtn = [[UIButton alloc]init];
    loginBtn.backgroundColor = Theme_Color;
    loginBtn.layer.cornerRadius = 5;
    [loginBtn setTitle:@"登       录" forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(loginBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    
    UIButton *registBtn = [[UIButton alloc]init];
    registBtn.layer.borderWidth = 1;
    registBtn.layer.cornerRadius = 5;
    registBtn.layer.borderColor = Theme_Color.CGColor;
    [registBtn setTitle:@"快速注册 " forState:UIControlStateNormal];
    [registBtn addTarget:self action:@selector(registBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [registBtn setTitleColor:Theme_Color forState:UIControlStateNormal];
    [self.view addSubview:registBtn];
    
    UIButton *forgetPassWord = [[UIButton alloc]init];
    forgetPassWord.layer.borderWidth = 1;
    forgetPassWord.layer.cornerRadius = 5;
    forgetPassWord.layer.borderColor = Theme_Color.CGColor;
    [forgetPassWord setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forgetPassWord setTitleColor:Theme_Color forState:UIControlStateNormal];
    [forgetPassWord addTarget:self action:@selector(forgetPWAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forgetPassWord];
    
    //布局
    [imageBtn mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.mas_equalTo(80),
        make.centerX.mas_equalTo(self.view),
        make.width.mas_equalTo(85),
        make.height.mas_equalTo(70);
    }];
    
    [_phoneText mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.mas_equalTo(imageBtn.mas_bottom).offset(64),
        make.left.mas_equalTo(18),
        make.right.mas_equalTo(-18),
        make.height.mas_equalTo(40);
    }];
    
    [_passWord mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.mas_equalTo(_phoneText.mas_bottom).offset(-1),
        make.left.mas_equalTo(18),
        make.right.mas_equalTo(-18),
        make.height.mas_equalTo(40);
    }];
    
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.mas_equalTo(_passWord.mas_bottom).offset(22),
        make.left.mas_equalTo(18),
        make.right.mas_equalTo(-18),
        make.height.mas_equalTo(40);
    }];
    
    [registBtn mas_makeConstraints:^(MASConstraintMaker *make){
        make.bottom.mas_equalTo(forgetPassWord.mas_top).offset(-15),
        make.left.mas_equalTo(18),
        make.right.mas_equalTo(-18),
        make.height.mas_equalTo(40);
    }];
    
    [forgetPassWord mas_makeConstraints:^(MASConstraintMaker *make){
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(-50),
        make.left.mas_equalTo(18),
        make.right.mas_equalTo(-18),
        make.height.mas_equalTo(40);
    }];
}

//按钮的点击事件
- (void)loginBtnAction{
    if ([_phoneText.text isValidateMobile]) {
        //登陆的网络请求
        //参数
        NSDictionary *parameters = @{
                                     @"phone":_phoneText.text,
                                     @"pass": _passWord.text,
                                     };
        [SVProgressHUD showWithStatus:@"登录中"];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer=[AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        [manager POST:@"http://115.28.152.130/tour/v1/login.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
            [SVProgressHUD showWithStatus:@"登录中"];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"%@<<><><><>>>>",dic);
            NSString *error = dic[@"code"];
            if (![dic[@"code"] isEqualToString:@"0000"]) {
                [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
            }else{
                //登陆成功
                //            [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
                [SVProgressHUD dismiss];
                //            Stockpile *stockpile = [Stockpile sharedStockpile];
                //            stockpile.identify = dic[@"object"][@"id"];
                //            NSLog(@"%@",stockpile.identify);
                
                [dic[@"object"][@"type"] saveToNSDefaultsWithKey:kType];
                NSNumber *personId = dic[@"object"][@"id"];
                NSString *personIdStr = personId.stringValue;
                [personIdStr saveToNSDefaultsWithKey:kId];
                NSNumber *age = dic[@"object"][@"age"];
                NSString *ageStr = age.stringValue;
                [ageStr saveToNSDefaultsWithKey:kAge];
                [dic[@"object"][@"photo"] saveToNSDefaultsWithKey:kPhotoUrl];
                [dic[@"object"][@"realName"] saveToNSDefaultsWithKey:kRealName];
                [dic[@"object"][@"nickName"] saveToNSDefaultsWithKey:kNickName];
                [dic[@"object"][@"sex"] saveToNSDefaultsWithKey:kSex];
                [dic[@"object"][@"clubID"] saveToNSDefaultsWithKey:kClubId];
                [dic[@"object"][@"phone"] saveToNSDefaultsWithKey:kPhone];
                [dic[@"object"][@"city"] saveToNSDefaultsWithKey:kCity];
                [dic[@"object"][@"card"] saveToNSDefaultsWithKey:kCard];
                [dic[@"object"][@"email"] saveToNSDefaultsWithKey:kEmail];
                [_passWord.text saveToNSDefaultsWithKey:kPass];
                
                //保存登陆状态
                [@"1" saveToNSDefaultsWithKey:kIsLogined];
                
                MainTabBarController *vc = [[MainTabBarController alloc]init];
                [self presentViewController:vc animated:NO completion:nil];
                
                //两个目前请求到的数据一样
                //            [self requestCurrentUser];
                [self requestGetUserWithId];
            }
            
        } failure:^(NSURLSessionDataTask *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"登陆失败"];
            [SVProgressHUD dismiss];
        }];
    }else{
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
    }
    
}

//获取当前登陆用户信息
- (void)requestCurrentUser{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/user/getCurrentUser.action" parameters:nil success:^(NSURLSessionDataTask *operation, id responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@<><>",dic);
        NSString *error = dic[@"code"];
        if (![dic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }else{
            [SVProgressHUD showSuccessWithStatus:@"获取用户详情成功"];
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"获取用户详情失败"];
    }];
}
//获取用户详情
- (void)requestGetUserWithId{
    
    NSDictionary *parameters = @{
                                 @"id":[NSString readToNSDefaultsWithKey:kId],
                                 };
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/user/getUser.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@<><>",dic);
        //获取当前时间
        NSDate *currentDate = [NSDate date];//获取当前时间，日期
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYYMMddHHmmssSSS"];
        NSString *dateString = [dateFormatter stringFromDate:currentDate];
        NSString *urlStr = dic[@"object"][@"user"][@"photo"];
        urlStr = [NSString stringWithFormat:@"%@%@%@",urlStr, @"?",dateString];
        [urlStr saveToNSDefaultsWithKey:kClubPhotoUrl];
        //身份证正反面
        NSString *cardPhotoFrontUrl = dic[@"object"][@"user"][@"cardPhotoFront"];
        cardPhotoFrontUrl = [NSString stringWithFormat:@"%@%@%@",cardPhotoFrontUrl, @"?",dateString];
        [cardPhotoFrontUrl saveToNSDefaultsWithKey:kIdCardFimgUrl];
        NSString *cardPhotoBackUrl = dic[@"object"][@"user"][@"cardPhotoBack"];
        cardPhotoBackUrl = [NSString stringWithFormat:@"%@%@%@",cardPhotoBackUrl, @"?",dateString];
        [cardPhotoBackUrl saveToNSDefaultsWithKey:kIdCardBimgUrl];
        
//        [dic[@"object"][@"club"][@"logo"] saveToNSDefaultsWithKey:kPhotoUrl];
        [dic[@"object"][@"club"][@"clubName"] saveToNSDefaultsWithKey:kClubName];
        [dic[@"object"][@"club"][@"clubSummary"] saveToNSDefaultsWithKey:kClubSummary];
        //club status
        [dic[@"object"][@"club"][@"status"] saveToNSDefaultsWithKey:kStatus];
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
    }];
}
- (void)forgetPWAction{
    ForgetPassWordVC *vc = [[ForgetPassWordVC alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
    nav.navigationBar.barTintColor = Theme_Color;
    [self presentViewController:nav animated:NO completion:nil];
}
- (void)registBtnAction{
    RegisterVC1 *vc = [[RegisterVC1 alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
    nav.navigationBar.barTintColor = Theme_Color;
    [self presentViewController:nav animated:NO completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
